package com.hdsx.validator.validate.processor;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.hdsx.validator.util.HdReflectUtils;
import com.hdsx.validator.validate.annotation.Regex;
import com.hdsx.validator.validate.log.ILog;

public class RegexProcessor implements IProcessor {

	public void process(Object obj,Field field,ILog log) throws Exception{
		Regex regex=field.getAnnotation(Regex.class);
		if(regex!=null)
		{
			boolean allowNull=regex.allowNull();
			String getName=HdReflectUtils.getInitial(field.getName());
			Method me=obj.getClass().getMethod(getName);
			Object value=me.invoke(obj);
			if(allowNull)
			{
				if(value!=null)
				{
					String regexStr=regex.express().getExpress();
					String str=String.valueOf(value);
					if(!match(regexStr, str))
					{
						String message=regex.message().equals("")?regex.message():regex.express().getMessage();
						log.record(message);
					}
				}
			}
			else
			{
				log.record(field.getName()+"为空");
			}
		}
	}
	protected boolean match(String regexStr,String str){
		Pattern pattern = Pattern.compile(regexStr);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}
}
